<?php
namespace app\admin\controller;


use app\admin\common\controller\Base;
use app\admin\common\model\User as UserModel;
use think\facade\Request;

class User extends Base
{
    /*
     * 会员列表
     */
    public function userList(UserModel $userModel)
    {
        $datas = $userModel->getPageList();

        $this->assign('datas',$datas);
        return $this->fetch('userList');
    }

    /*
     * 会员编辑
     */
    public function editUser(UserModel $userModel)
    {
        $id = Request::param('id');

        if (empty($id)) {
            $this->error('数据ID丢失');
        }

        $info = $userModel->getInfoById($id);

        $this->assign('info',$info);
        return $this->fetch('editUser');
    }

    /*
     * 编辑会员操作
     */
    public function editUserDo(UserModel $userModel)
    {
        $params = Request::param();

        $rule = 'app\admin\validate\EditUser';

        $result = $this->validate($params, $rule);

        if (true !== $result) {
            $this->error($result);
        }

        //如果上传的图片不为空,再生成$param['avatar'],否则,不生成
        //生成的$param['avatar']用于修改UserModel中avatar的值
        if (!empty(Request::file())) {

            //删除id对应的图片
            $userModel->delAvatar($params['id']);

            $file = Request::file('avatar');
            $info = $file->validate([
                'size'  =>  500000000,
                'ext'   =>  'jpeg,jpg,png,gif',
            ])->move('uploads/avatar/');

            if ($info) {
                $params['avatar'] = $info->getSaveName();
            } else {
                $this->error($file->getError());
            }
        }

        //如果密码为空,则删除$params['password'],否则,$params['password']加密
        //如果删除$params['password'],则更新的时候不更新UserModel中的password
        if (empty($params['password'])) {
            unset($params['password']);
        } else {
            $params['password'] = md5($params['password']);
        }

        $res = $userModel->editUser($params);

        if ($res) {
            $this->success('更新成功','User/userList');
        }

        $this->error('更新失败');
    }

    /*
     * 删除会员操作
     */
    public function delUser(UserModel $userModel)
    {
        $id = Request::param('id');

        if (empty($id)) {
            $this->error('数据ID丢失');
        }

        $res = $userModel->delUser($id);

        if ($res) {
            $this->success('删除成功','User/userList');
        }

        $this->error('删除失败');
    }
}